var winston = require('winston');
var mysql = require('mysql');
var ejs = require('ejs');
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));
var path = require('path');
var API_KEY = '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';

var sendgrid  = require('sendgrid')(API_KEY);


module.exports = function(pool, req, res, next){
	var uriMap = req.params.uriMap;
	var info = req.body.data;
	if(typeOf(info) === 'string'){
		info = JSON.parse(printItems);
	}
	//var emailRE = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
	var emailRE = /^(?:[-\w])+(?:\.[-\w]+)*@(?:[-\w])+(?:(?:\.[-\w]+)+)$/;
	var eventId, email, name;
	email = info.email;
	name = info.name || '';
	if(!emailRE.test(email)){
		res.status(400).send('bad email format');
	}

	
	var queryString = 'SELECT share_content FROM share_list where uri_map="' + uriMap + '"';
	pool.getConnection(function(err, connection){
		if(err){
			winston.error('DB connection error: ' + err);
			res.status(500).send('DB connection error: ' + err);
		}
		connection.query(queryString, function(err, rows){
			if(err){
				winston.error('DB query error: ' + err);
				res.status(500).send('DB query error: ' + err);
			}else{
				if(rows.length > 0){
					var shareContent = rows[0].share_content;
					queryString = 'SELECT event_id, filename, is_portrait FROM photo_list where photo_id RLIKE "' + shareContent + '"';
					connection.query(queryString, function(err, rows){
						if(err){
							winston.error('DB query error: ' + err);
							res.status(500).send('DB query error: ' + err);
						}else{
							res.send({msg:'0k'});
							eventId = rows[0]['event_id'];
							rows.forEach(function(row){
								var url = req.protocol + "://" + req.hostname + "/assets/" + row.event_id + "/" + row.filename;
								row.url = url;
							});
							rows.qrCode = req.protocol + "://" + req.hostname + "/qr/" + encodeURIComponent(req.protocol + "://" + req.hostname + "/share/" + uriMap);
							rows.host = req.protocol + "://" + req.hostname;
							rows.name = name;
							rows.uri = rows.host + "/share/" + uriMap;

							var pathToEmailConfig = path.join(__dirname, "..", "events", eventId + "","email.json" );
							var pathToEmailContent = path.join(__dirname, "..", "templates/email", eventId + ".ejs");
							Promise.join(fs.readFileAsync(pathToEmailConfig), fs.readFileAsync(pathToEmailContent)).then(function(args){
								emailConfig = JSON.parse(args[0].toString());
								emailContent = args[1].toString();
								
								var emailObject     = new sendgrid.Email({
																  to:       email,
																  from:     emailConfig.from,
																  fromname: emailConfig.fromName,
																  replyto: 	emailConfig.replyTo,
																  subject:  emailConfig.subject,
																  html:     ejs.render(emailContent, {data: rows})
																});

								sendgrid.send(emailObject, function(error, json) {
								  	queryString = 'INSERT INTO email_sent (email, name, event_id, uri_map, is_success, timestamp) VALUES (?, ?, ?, ?, ?, ?)';
										var isSuccess = 1;
								    if(error){
								        winston.error(error);
												isSuccess = 0;												
								    }else{
								        winston.info('Message sent: ' + json.message);
								    }
										// record to db
										var params = [email, name, eventId, uriMap,  isSuccess, String.from(Date.now())];
										connection.query(mysql.format(queryString, params), function(err){
											if(err){
												winston.error('DB query error: ' + err);
											}
										});
								});

								
							}).catch(function(err){
								if(err){
									winston.error(err);
								}
							});
							


						}
					});
					
				}else{
					res.end('Search 0 photo from the ' + uriMap);
				}
			}
			connection.release();
		});
	});
	
	
}